/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package cryptoprovider

import (
	"crypto/sha256"
	"encoding/hex"
	"hash"

	"strings"
)

const (
	defaultSalt = "did1029!@"
)

type SHA2 struct {
	salt    string
	encoder hash.Hash
}

func NewSHA2(salt []byte) *SHA2 {
	if salt == nil {
		salt = []byte(defaultSalt)
	}
	return &SHA2{
		salt: string(salt),
	}
}

func (ap *SHA2) Encrypt(plain string) string {
	return sha256Encode(plain + ap.salt)
}

func (ap *SHA2) Check(originCipher, attempCipher string) bool {
	cip := ap.Encrypt(attempCipher)
	if strings.EqualFold(originCipher, cip) {
		return true
	}
	return false
}

func (ap *SHA2) Decrypt(cipher string) (string, error) {
	return cipher, nil
}

func sha256Encode(src string) string {
	m := sha256.New()
	m.Write([]byte(src))
	res := hex.EncodeToString(m.Sum(nil))
	return res
}
